package com.ncst.backend.controller;

import com.ncst.backend.common.Result;
import com.ncst.backend.domain.Prescription;
import com.ncst.backend.service.PrescriptionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 处方控制器
 */
@Api(tags = "处方管理")
@Slf4j
@RestController
@RequestMapping("/prescriptions")
public class PrescriptionController {

    @Autowired
    private PrescriptionService prescriptionService;

    @ApiOperation("查询所有处方记录")
    @GetMapping
    public Result<List<Prescription>> getAll() {
        return Result.success(prescriptionService.getAll());
    }

    @ApiOperation("根据条件查询处方记录")
    @PostMapping("/search")
    public Result<List<Prescription>> getByCondition(@ApiParam("查询条件") @RequestBody Prescription prescription) {
        return Result.success(prescriptionService.getByCondition(prescription));
    }


//    @ApiOperation("根据条件查询处方记录")
//    @PostMapping("/searchby")
//    public Result<List<Prescription>> getByCaseNumberAndRealName(
//            @ApiParam("病历号") String caseNumber,
//            @ApiParam("姓名") String realName) {
//        return Result.success(prescriptionService.getByCaseNumberAndRealName(caseNumber, realName));
//    }
    @ApiOperation("分页查询处方记录")
    @GetMapping("/page")
    public Result<List<Prescription>> getByPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("挂号ID") @RequestParam(required = false) Integer registerId,
            @ApiParam("药品ID") @RequestParam(required = false) Integer drugId,
            @ApiParam("药品状态") @RequestParam(required = false) String drugState) {
        Prescription prescription = new Prescription();
        prescription.setRegisterId(registerId);
        prescription.setDrugId(drugId);
        prescription.setDrugState(drugState);
        return Result.success(prescriptionService.getByPage(pageNum, pageSize, prescription));
    }

    @ApiOperation("统计处方记录总数")
    @GetMapping("/count")
    public Result<Long> countAll() {
        return Result.success(prescriptionService.countAll());
    }

    @ApiOperation("根据条件统计处方数量")
    @PostMapping("/count")
    public Result<Long> countByCondition(@ApiParam("查询条件") @RequestBody Prescription prescription) {
        return Result.success(prescriptionService.countByCondition(prescription));
    }

    @ApiOperation("新增处方记录")
    @PostMapping
    public Result<Void> save(@ApiParam("处方信息") @RequestBody Prescription prescription) {
        return prescriptionService.save(prescription) ? Result.success("新增成功") : Result.error("新增失败");
    }

    @ApiOperation("批量新增处方记录")
    @PostMapping("/batch")
    public Result<Void> saveBatch(@ApiParam("处方列表") @RequestBody List<Prescription> list) {
        if (list == null || list.isEmpty()) {
            return Result.error("处方列表不能为空");
        }
        
        // 获取挂号ID
        Integer registerId = list.get(0).getRegisterId();
        if (registerId == null) {
            return Result.error("挂号ID不能为空");
        }
        
        try {
            // 先删除该病人的所有处方记录
            Prescription prescription = new Prescription();
            prescription.setRegisterId(registerId);
            List<Prescription> oldPrescriptions = prescriptionService.getByCondition(prescription);
            if (oldPrescriptions != null && !oldPrescriptions.isEmpty()) {
                List<Integer> ids = oldPrescriptions.stream().map(Prescription::getId).collect(java.util.stream.Collectors.toList());
                prescriptionService.removeByIds(ids);
            }
            
            // 再批量插入新的处方记录
            return prescriptionService.saveBatch(list) ? Result.success("批量新增成功") : Result.error("批量新增失败");
        } catch (Exception e) {
            log.error("批量保存处方失败: {}", e.getMessage());
            return Result.error("批量新增失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("根据挂号ID查询处方记录")
    @GetMapping("/by-register-id")
    public Result<List<Prescription>> getByRegisterId(@ApiParam("挂号ID") @RequestParam Integer registerId) {
        if (registerId == null) {
            return Result.error("挂号ID不能为空");
        }
        
        Prescription prescription = new Prescription();
        prescription.setRegisterId(registerId);
        List<Prescription> prescriptions = prescriptionService.getByCondition(prescription);
        return Result.success(prescriptions);
    }

    @ApiOperation("根据ID更新处方记录")
    @PutMapping("/{id}")
    public Result<Void> updateById(@ApiParam("处方ID") @PathVariable Integer id, @ApiParam("处方信息") @RequestBody Prescription prescription) {
        prescription.setId(id);
        return prescriptionService.updateById(prescription) ? Result.success("更新成功") : Result.error("更新失败");
    }

    @ApiOperation("根据条件查询处方记录")
    @PostMapping("/searchby")
    public Result<List<Prescription>> getByCaseNumberAndRealName(
          @RequestBody  PrescriptionQueryParam  param) {
        return Result.success(prescriptionService.getByCaseNumberAndRealName(param.getCaseNumber(), param.getRealName()));
    }

    @ApiOperation("批量删除处方记录")
    @DeleteMapping("/batch")
    public Result<Void> removeByIds(@ApiParam("处方ID列表") @RequestBody List<Integer> ids) {
        return prescriptionService.removeByIds(ids) ? Result.success("批量删除成功") : Result.error("批量删除失败");
    }

    // 带有路径变量的方法放在最后，避免与其他固定路径冲突
    @ApiOperation("根据ID查询处方记录")
    @GetMapping("/{id}")
    public Result<Prescription> getById(@ApiParam("处方ID") @PathVariable Integer id) {
        Prescription prescription = prescriptionService.getById(id);
        return prescription != null ? Result.success(prescription) : Result.notFound("处方记录不存在");
    }

    @ApiOperation("根据ID删除处方记录")
    @DeleteMapping("/{id}")
    public Result<Void> removeById(@ApiParam("处方ID") @PathVariable Integer id) {
        return prescriptionService.removeById(id) ? Result.success("删除成功") : Result.error("删除失败");
    }

    @Data
    static class PrescriptionQueryParam {
        private String caseNumber;
        private String realName;
    }
}
